package com.example.minisqlite;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TableDefinition implements Serializable {

    private final int tableId;
    private final String name;
    private final List<ColumnDefinition> columns;
    private final int primaryKeyIndex;
    private long nextRowId;

    public TableDefinition(int tableId, String name, List<ColumnDefinition> columns, int primaryKeyIndex) {
        this.tableId = tableId;
        this.name = name;
        this.columns = new ArrayList<>(columns);
        this.primaryKeyIndex = primaryKeyIndex;
        this.nextRowId = 1L;
    }

    public int getTableId() {
        return tableId;
    }

    public String getName() {
        return name;
    }

    public List<ColumnDefinition> getColumns() {
        return Collections.unmodifiableList(columns);
    }

    public int getPrimaryKeyIndex() {
        return primaryKeyIndex;
    }

    public boolean hasPrimaryKey() {
        return primaryKeyIndex >= 0;
    }

    public synchronized long nextRowId() {
        return nextRowId++;
    }

    public synchronized void ensureRowId(long rowId) {
        if (rowId >= nextRowId) {
            nextRowId = rowId + 1;
        }
    }

    public int findColumnIndex(String column) {
        for (int i = 0; i < columns.size(); i++) {
            if (columns.get(i).getName().equalsIgnoreCase(column)) {
                return i;
            }
        }
        return -1;
    }
}
